﻿//
// image block
//
package com.artworld {
	import flash.display.Sprite;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.geom.Matrix;
	import com.adobe.images.JPGEncoder;
	
	import flash.net.URLRequest;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLRequestHeader;
	import flash.net.URLRequestMethod;
	import flash.net.URLLoader;
	import flash.net.URLVariables;
	import flash.utils.ByteArray;
	
	public class ImageBlock extends Bitmap {
		// data
		private var updated:Boolean = false;
		// setup
		public function ImageBlock(){
			bitmapData = new BitmapData(100,100);
		}
		public function draw(sp:Sprite):void{
			if(hitTestObject(sp)){
				updated = true;
			}
			var mtx:Matrix = new Matrix(1,0,0,1,x*-1,y*-1);
			bitmapData.draw(sp,mtx);
		}
		//loading
		public function loadImage():void{
			// the idea is that we can load the image based on it's location in the
			var id:String = (x/100)+"x"+(y/100);
			var url:String = "http://www.sophiadaniels.com/artworld/image.php?id="+id+"&r="+Math.random();
			var loader:Loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onImageLoaded);
			loader.load(new URLRequest(url));
			trace(url);
		}
		private function onImageLoaded(e:Event):void{
			trace("loaded",(x/100)+"x"+(y/100));
			bitmapData = e.target.content.bitmapData;
		}
		//saving
		function saveImage(){
			if(updated){
				var id:String = (x/100)+"x"+(y/100);
				var jpgEncoder:JPGEncoder = new JPGEncoder(90);
				var jpgStream:ByteArray = jpgEncoder.encode(bitmapData);
				
				var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
				var serverRequest:URLRequest = new URLRequest("http://www.sophiadaniels.com/artworld/upload.php?id="+id);
				serverRequest.method = URLRequestMethod.POST;
				serverRequest.requestHeaders.push(header);
				var _vars = new URLVariables();
				serverRequest.data = jpgStream;
				var loadUrl:URLLoader = new URLLoader();
				loadUrl.load(serverRequest)
				
				updated = false;
			}
		}
	}
}